<template>
  <main-card
    :title="`应用详情（${appInfo.name}）`"
    :crumbs="crumbs"
    :screen-style-obj="{ padding: '0 0 20px 0' }"
    is-fixed-body
    :loading="loading"
  >
    <template #screen-space>
      <a-row class="time-module">
        <a-col class="mr-16 label">应用创建时间</a-col>
        <a-col class="mr-24 val">{{ appInfo.createTime }}</a-col>
        <a-col class="mr-24">
          <svg xmlns="http://www.w3.org/2000/svg" width="2" height="20" viewBox="0 0 2 20" fill="none">
            <path d="M1 0V20" stroke="#D9D9DB" />
          </svg>
        </a-col>
        <a-col class="mr-16 label">应用更新时间</a-col>
        <a-col class="mr-24 val">{{ appInfo.updateTime }}</a-col>
      </a-row>
    </template>
    <template #tool-btn>
      <div class="flex gap-8">
        <a-button type="default" class="icon-with-btn" @click.stop="openDeleteModal()">
          <i class="iconfont icon-delete-bin-line"></i>
          <span class="text">删除</span>
        </a-button>
        <a-button type="default" class="icon-with-btn" @click.stop="goEdit()">
          <i class="iconfont icon-edit-line"></i>
          <span class="text">编辑</span>
        </a-button>
      </div>
    </template>

    <div class="page-body">
      <!-- 应用信息 -->
      <app-info :info-arr="appInfoArr" :app-id="appId" />
      <div class="tabs">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane v-for="tab in tabs" :key="tab.key" :tab="tab.name">
            <a-space direction="vertical" class="w-[100%]">
              <!-- API服务 -->
              <template v-if="activeKey === 1">
                <a-collapse v-for="apiItem in appInfo.apiVOList" :key="apiItem.id">
                  <a-collapse-panel key="1" :header="apiItem.algoName">
                    <!-- :scroll="{ x: 'auto' }" -->
                    <a-table
                      :style="{ width: '100%' }"
                      :scroll="tableScroll"
                      :columns="apiTableColumns"
                      class="header-right-angle admin-table"
                      :data-source="apiItem.appServeList"
                      :pagination="false"
                    >
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex == 'version'"> {{ record.version }} </template>
                        <template v-else-if="column.dataIndex == 'usedCallNum'">
                          {{ record.usedCallNum }}/{{ record.totalCallNum }}
                        </template>
                        <template v-else-if="column.dataIndex == 'operateMethodStatus'">
                          <a-tooltip v-if="statusObj[record.operateMethodStatus].tooltip" placement="bottom">
                            <template #title>
                              <span>{{ record.operateMethodStatus?.substring(1) }}时间 {{ record?.operateMethodTime || '' }}</span>
                            </template>
                            {{ record.operateMethodStatus || '' }}
                          </a-tooltip>
                          <span v-else>{{ record.operateMethodStatus || '' }}</span>
                        </template>
                        <template v-else-if="column.dataIndex == 'time'">
                          {{ record.beforeValidTime }} ~ {{ record.afterValidTime }}
                        </template>
                        <template v-else-if="column.dataIndex == 'docs'">
                          <a-button type="link" @click="previewDoc(record.operateMethodId)"> 技术文档</a-button>
                        </template>
                        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
                      </template>
                    </a-table>
                  </a-collapse-panel>
                </a-collapse>
                <a-empty v-if="appInfo.apiVOList?.length === 0" :image="simpleImage" />
              </template>
              <!-- SDK服务 -->
              <template v-else-if="activeKey === 2">
                <a-collapse v-for="askItem in appInfo.sdkVOList" :key="askItem.id">
                  <a-collapse-panel key="1" :header="askItem.algoName">
                    <a-table
                      :style="{ width: '100%' }"
                      :scroll="{ x: 'auto' }"
                      :columns="sdkTableColumns"
                      :data-source="askItem.appServeList"
                      :pagination="false"
                    >
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex == 'version'"> {{ record.version }} </template>
                        <template v-else-if="column.dataIndex == 'authType'">
                          {{ record.authType === 1 ? '联网激活' : '离线激活' }}
                        </template>
                        <template v-else-if="column.dataIndex == 'openNum'">
                          {{ record.authType === 1 ? record.usedActivateNum : '-' }}/{{ record.totalActivateNum }}
                        </template>
                        <template v-else-if="column.dataIndex == 'tools'">
                          <a-button type="link" class="mr-20" @click="handleOpenDeviceCodeModal(record.id)">设备码</a-button>
                          <a-button type="link" class="mr-20" @click="downloadSdk(record.operateMethodId)">下载</a-button>
                          <a-button type="link" class="mr-20" @click="previewDoc(record.operateMethodId)"> 技术文档</a-button>
                        </template>
                        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
                      </template>
                    </a-table>
                  </a-collapse-panel>
                </a-collapse>
                <a-empty v-if="appInfo.sdkVOList?.length === 0" :image="simpleImage" />
              </template>
            </a-space>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </main-card>

  <device-code ref="deviceCodeRef" />

  <delete-confirm-dialog
    v-model:show="showDeleteModal"
    title="确认删除"
    msg="删除应用将导致所含服务失效，请确认操作"
    label="请输入应用编号"
    :confirm-name="appInfo.number"
    @ok="deleteApp"
  />
</template>

<script lang="ts" setup>
  import { Empty, message } from 'ant-design-vue'
  import { computed, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import { Crumb } from '@/components/MainCard/index.vue'
  import router from '@/router'
  import { appApi, fetchDownload } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'
  import { waitLoading } from '@/utils'

  // eslint-disable-next-line
  import AppInfo, { ArrItem } from './components/AppInfo.vue'
  import DeviceCode from './components/DeviceCode.vue'
  import { statusObj } from './options'
  import { AppDetail } from './types'

  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

  const route = useRoute()

  const crumbs = computed<Crumb[]>(() => [
    {
      name: '应用列表',
      path: '/ai-app/app-list/list'
    },
    {
      name: `应用详情（${appInfo.value.name}）`
    }
  ])

  const appId = (route.params.id as string) || ''
  const appInfo = ref<AppDetail>({
    id: ''
  })
  const appInfoArr = ref<ArrItem[]>([]) // 应用信息数组
  const activeKey = ref<1 | 2>(1) // 1:API服务 2:SDK服务
  const tabs = computed(() => [
    {
      key: 1,
      name: `API服务`
    },
    {
      key: 2,
      name: `SDK服务`
    }
  ])

  watch(appInfo, val => {
    appInfoArr.value = [
      { label: '应用编号', val: val.number || '' },
      { label: '应用名称', val: val.name || '' },
      { label: '在线服务ID', val: val.onlineId || '' },
      { label: 'API Key', val: val.apiKey || '' },
      { label: 'Secret Key', val: val.secretKey || '' },
      { label: 'License ID', val: val.licenseId || '', type: 'license' },
      { label: '序列号', val: val.serialNum || '' },
      { label: '应用描述', val: val.content || '' }
    ]
  })

  const { loading, runAsync: getClientInfoRun } = useRequest<ResponseData<AppDetail>>(appApi.detail(appId), {
    onSuccess: res => {
      appInfo.value = res.data
      console.log(res.data)
    }
  })

  const getClientInfo = async () => {
    getClientInfoRun({
      appServeType: activeKey.value
    })
  }

  watch(activeKey, () => getClientInfo(), { immediate: true })

  // 下载sdk文件
  const downloadSdk = async (operateMethodId: string) => {
    const { data } = await appApi.getSdkFileUrl(operateMethodId)()

    waitLoading(fetchDownload(data.fileUrl, data.fileName), {
      loadingText: '数据准备中,请耐心等待...',
      errorText: '文件下载失败',
      successText: '文件下载成功'
    })
  }

  // 设备码
  const deviceCodeRef = ref()
  const handleOpenDeviceCodeModal = async (id: string) => {
    try {
      deviceCodeRef.value.openModal()
      deviceCodeRef.value.changeLoading(true)
      const { data } = await appApi.getSerialDeviceCode(id)()
      deviceCodeRef.value.changeLoading(false)
      deviceCodeRef.value.setDetailInfo(data)
    } catch (error) {
      deviceCodeRef.value.changeLoading(false)
    }
  }

  const previewDoc = async (operateId: string) => {
    const { data } = await appApi.getDownloadDocumentUrl({}, { urlParams: { operateId } })

    window.open(data.fileUrl)
  }
  /* API,SDK展示逻辑-------------------------------------------------------------------- */
  const apiTableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: 'APICode',
        dataIndex: 'apiCode',
        width: 100
      },
      {
        title: '调用量',
        dataIndex: 'usedCallNum',
        width: 100
      },
      {
        title: 'QPS',
        dataIndex: 'qps',
        width: 100
      },
      {
        title: '应用服务状态',
        dataIndex: 'appStatus',
        width: 120
      },
      {
        title: '算法运行状态',
        dataIndex: 'operateMethodStatus',
        width: 120
      },
      {
        title: '有效期',
        dataIndex: 'time',
        minWidth: 200
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 190
      },
      {
        title: '',
        dataIndex: 'docs',
        fixed: 'right',
        width: 96
      }
    ])
  )

  // const scrollX = computed(() => {
  //   return sdkTableColumns.value.reduce((prev, curr) => {
  //     return prev + (curr.width as number)
  //   }, 0)
  // })
  const tableScroll = computed(() => {
    const scrollX = sdkTableColumns.value.reduce((prev: any, curr: any) => {
      console.log('++++', curr, prev, prev + (curr.width as number))

      return prev + (curr.width as number)
    }, 0)
    console.log('x:', scrollX)

    return {
      x: scrollX > 450 ? scrollX : undefined
    }
  })
  const sdkTableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: '平台',
        dataIndex: 'platform',
        width: 180
      },
      {
        title: '语言',
        dataIndex: 'language',
        width: 100
      },
      {
        title: '授权方式',
        dataIndex: 'authType',
        width: 140
      },
      {
        title: '已激活/可激活设备数',
        dataIndex: 'openNum',
        width: 160
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 160
      },
      {
        title: '',
        dataIndex: 'tools',
        fixed: 'right',
        width: 96
      }
    ])
  )

  /* 删除逻辑 -------------------------------------------------------------------------------- */
  const showDeleteModal = ref(false)
  const openDeleteModal = async () => {
    showDeleteModal.value = true
  }
  const deleteApp = async () => {
    await appApi.del(appInfo.value!.id)()
    message.success('操作成功')
    showDeleteModal.value = false
    router.push('/ai-app/app-list/list')
  }

  const goEdit = () => {
    router.push(`/ai-app/app-list/edit?id=${appInfo.value!.id}`)
  }

  /* -------------------------------------------------------------------- */
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';

  .time-module {
    display: flex;
    align-items: center;
    padding: 8px 24px;
    font-size: 12px;
    background: @background3;
    border-radius: 6px;

    .label {
      color: @text03;
    }

    .val {
      color: @text01;
    }
  }

  .page-body {
    display: flex;
    height: 100%;

    .tabs {
      flex: 1;
      // height: 100%;
      display: flex;
      overflow: hidden;

      .ant-tabs {
        width: 100%;

        :deep(.ant-tabs-content-holder) {
          overflow-y: auto;
        }
      }

      .ant-collapse {
        width: 100%;

        :deep(.ant-collapse-content-box) {
          padding: 0;
        }
      }
    }
  }
</style>
